package com.hanyxx.thread;

import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;

/**
 * @author layman
 * @date 2021/2/7
 */
public class Demo14 {
    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        Demo14Chef chef = new Demo14Chef(lock);
        Demo14Consumer consumer = new Demo14Consumer(lock);
        chef.setName("大厨食神");
        consumer.setName("吃货layman");
        consumer.start();
        Thread.sleep(500);
        chef.start();
    }
}
class Meal{
    public static volatile List<String> baozi = new ArrayList<>();
    public static Long sleepTime = 0L;
}
//生产者
class Demo14Chef extends Thread{
    private Object lock;
    public Demo14Chef(Object lock){
        this.lock = lock;
    }
    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                while (Meal.baozi.size() == 1) {
                    System.out.println("包子还没吃完，等着吃货来吃包子。");
                    System.out.println("---------------------------");
                    //Thread.sleep(Meal.sleepTime);
                    lock.wait();
                }
                while (Meal.baozi.size() == 0) {
                    Meal.baozi.add("一个包子");
                    System.out.println("做了一个大包子， 通知吃货来吃包子");
                    System.out.println("------------------------------");
                    //Thread.sleep(Meal.sleepTime);
                    lock.notifyAll();
                }
            }
        }
    }
}
//消费者
class Demo14Consumer extends Thread{
    private Object lock;
    public Demo14Consumer(Object lock){
        this.lock = lock;
    }
    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                while (Meal.baozi.size() == 0) {
                    System.out.println("没包子吃，等着厨师做包子。");
                    System.out.println("----------------------");
                    //Thread.sleep(Meal.sleepTime);
                    lock.wait();
                }
                while (Meal.baozi.size() == 1) {
                    Meal.baozi.clear();
                    System.out.println("吃货把包子吃光了，通知厨师做包子");
                    System.out.println("-----------------------------");
                    //Thread.sleep(Meal.sleepTime);
                    lock.notifyAll();
                }
            }
        }
    }
}
